<template>
  <view class="user-center-container">
    <!-- 顶部返回区域 -->
    <view class="top-bar">
      <view class="back-btn" @click="gotoHome">
        <image
            class="back-icon"
            src="/static/icons/back-arrow.png"
            mode="aspectFit"
        />
      </view>
      <view class="page-title">个人中心</view>
    </view>
    <!-- 用户信息头部区域 -->
    <view class="user-header">
      <image :src="userInfo?.avatar || '/static/avatar/user.png'" class="user-avatar" mode="widthFix" />
      <view class="user-name-area">
        <view class="user-name">{{ userInfo?.username || '小棒棒' }}</view>

        <!-- 模块1：最新套餐简要信息 -->
        <view class="member-tag" v-if="validPackages.length > 0">
          {{ validPackages[0].packageName }} · 剩余{{ validPackages[0].remainingDays }}天
        </view>
        <view class="member-tag no-package" v-else>
          暂无套餐
        </view>
      </view>
    </view>

    <!-- 模块2：套餐详情卡片（展示所有有效套餐） -->
    <view class="package-cards" v-if="validPackages.length > 0">
      <view
          class="package-card"
          v-for="(pkg, index) in validPackages"
          :key="pkg.id"
      >
        <image src="/static/icons/gift.png" class="package-icon" mode="widthFix" />
        <view class="package-detail">
          <view class="package-title">{{ pkg.packageName }}</view>
          <view class="package-desc">{{ pkg.serviceDesc }}</view>
          <view class="package-time">
            购买时间: {{ formatDate(pkg.startTime) }}
          </view>
          <view class="package-days">
            有效期至: {{ formatDate(pkg.endTime) }} (剩余{{ pkg.remainingDays }}天)
          </view>
        </view>
      </view>
    </view>
    <view class="no-package-card" v-else>
      <text class="no-package-text">您还未购买任何套餐，点击下方按钮选购吧～</text>
      <button class="buy-btn" @click="gotoBuyPackage">立即选购套餐</button>
    </view>

    <!-- 功能按钮区 -->
    <view class="function-buttons">
      <view class="feedback-btn" @click="gotoFeedbackList">
        <image src="/static/icons/feedback.png" class="feedback-icon" mode="widthFix" />
        <text class="feedback-text">我要反馈</text>
      </view>
      <view class="logout-btn" @click="logout">
        <image src="/static/icons/logout.png" class="logout-icon" mode="widthFix" />
        <text class="logout-text">退出登录</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import request from '@/utils/request.js';

// 响应式变量
const userInfo = ref({});
const packageList = ref([]);
const validPackages = ref([]); // 存储所有有效套餐

// 格式化日期
const formatDate = (dateTime) => {
  if (!dateTime) return '未知';
  const date = new Date(dateTime);
  return date.toLocaleDateString();
};

// 页面显示时触发
onShow(async () => {
  try {
    // 1. 获取用户信息
    const userRes = await request.get('agent/user/userDetail');
    userInfo.value = userRes || {};

    // 2. 获取套餐列表
    const packageRes = await request.get('agent/userPackage/all');
    packageList.value = Array.isArray(packageRes) ? packageRes : [];

    // 3. 筛选所有有效套餐（isValid === 1）
    validPackages.value = packageList.value.filter(pkg => pkg.isValid === 1);

    // 4. 按购买时间（startTime）降序排序，确保最新套餐在最前
    validPackages.value.sort((a, b) => new Date(b.startTime) - new Date(a.startTime));

  } catch (error) {
    uni.showToast({ title: '数据获取失败', icon: 'none' });
    console.error('接口异常:', error);
    userInfo.value = {};
    packageList.value = [];
    validPackages.value = [];
  }
});

// 跳转到反馈列表
const gotoFeedbackList = () => {
  uni.redirectTo({ url: '/pages/feedback/index' });
};
// 跳转到首页
const gotoHome = () => {
  uni.redirectTo({ url: '/pages/home/index' });
};

// 退出登录
const logout = () => {
  uni.showToast({ title: '退出登录成功', icon: 'success' });
  setTimeout(() => {
    uni.reLaunch({ url: '/pages/login/index' });
  }, 1500);
};

// 跳转到套餐购买页
const gotoBuyPackage = () => {
  uni.navigateTo({ url: '/pages/package/index' });
};
</script>

<style scoped>
/* 页面主容器 */
.user-center-container {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 顶部栏样式 */
.top-bar {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  margin-bottom: 15px;
  width: 100%;
}

.back-btn {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.back-icon {
  width: 24px;
  height: 24px;
}

.page-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  flex: 1;
  text-align: center;
}

/* 用户信息头部 */
.user-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
  width: 100%;
}
.user-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  border: 2px solid #ffffff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}
.user-name-area {
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex: 1;
}
.user-name {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

/* 模块1：会员标签 */
.member-tag {
  font-size: 14px;
  padding: 4px 10px;
  border-radius: 16px;
  background-color: #f0f0f0;
  color: #999;
  width: fit-content;
  display: flex;
  align-items: center;
}
.member-tag.no-package {
  background-color: #fff;
  border: 1px dashed #ddd;
}

/* 立即选购按钮样式（居中且醒目） */
.buy-btn {
  background-color: #409eff;
  color: #fff;
  font-size: 14px;
  padding: 8px 20px;
  border-radius: 8px;
  border: none;
  line-height: normal;
}

/* 模块2：套餐卡片容器（多套餐垂直排列） */
.package-cards {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
}

/* 单个套餐卡片 */
.package-card {
  width: 100%;
  background-color: #fff;
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  gap: 15px;
}
.package-icon {
  width: 50px;
  height: 50px;
  flex-shrink: 0;
}
.package-detail {
  display: flex;
  flex-direction: column;
  gap: 6px;
  flex: 1;
}
.package-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}
.package-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}
.package-time {
  font-size: 14px;
  color: #999;
}
.package-days {
  font-size: 14px;
  color: #999;
}

/* 无套餐时的提示卡片（内容居中） */
.no-package-card {
  width: 100%;
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  text-align: center;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}
.no-package-text {
  font-size: 14px;
  color: #666;
}

/* 功能按钮区域 */
.function-buttons {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 15px;
}
.feedback-btn, .logout-btn {
  width: 100%;
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  gap: 10px;
  transition: all 0.2s ease;
}
.feedback-btn:active, .logout-btn:active {
  background-color: #f9f9f9;
}
.feedback-icon, .logout-icon {
  width: 24px;
  height: 24px;
}
.feedback-text, .logout-text {
  font-size: 16px;
  color: #333;
  flex: 1;
}
</style>